#include "simulator.h"
#include "cmdparse.h"
#include "randomizer.h"

#include <QDebug>

const char* g_nodeInfoFileName = "describe_node.json";



/**
 * @brief SimulatorCmd2SerialPortData　将模拟的信号转换成串口数据
 * @param cmd_
 * @return
 */
SerialPortData SimulatorCmd2SerialPortData(const SimulatorCmd &cmd_)
{
    SerialPortData _re;
    _re.type = static_cast<char>(cmd_.m_nodeFlag);
    _re.cmd = cmd_.m_cmdID;
    if (cmd_.m_cmdID == SimulatorCmd::NETWORKBUILD)
    {
        _re.data.append(cmd_.m_qstrSendNetWorkID + "|"
                        + cmd_.m_qstrParentNetWorkID
                        + "|" + cmd_.m_DeviceName + "||");

    } else if (cmd_.m_cmdID == SimulatorCmd::TEMPERATURE) {
        _re.data.append(cmd_.m_qstrSendNetWorkID + "|"
                        + QString::number(Randomizer::creat(cmd_.m_qstrContext.toInt() == 0
                                                            ? 89 : cmd_.m_qstrContext.toInt()))
                        + "|" + cmd_.m_DeviceName + "||");
    } else {
        _re.data.append(cmd_.m_qstrSendNetWorkID
                        + "||" + cmd_.m_DeviceName + "||");
    }

    return _re;
}

Simulator::Simulator(QObject *parent) :
    QObject(parent)
{
    help_parse();
    connect(&m_timer, SIGNAL(timeout()), this, SLOT(SltScan()));
    m_timer.setInterval(1000);

}


Simulator::~Simulator()
{

}

void Simulator::SltScan()
{
    for (type_cmds::Iterator _ite = m_Cmds.begin(); _ite != m_Cmds.end();)
    {
        //超时
        if (++(*_ite).m_nCurrentSec == (*_ite).m_nT)
        {
            help_doData(SimulatorCmd2SerialPortData((*_ite)));
            if ((*_ite).m_circleFlag == SimulatorCmd::CIRCLENO)
            {
                m_Cmds.erase(_ite);
                continue;

            }
            //CIRCLEYES
            (*_ite).m_nCurrentSec = 0;


        }
        ++_ite;
    }
}
/////
/// \brief Simulator::help_parse
///
void Simulator::help_parse()
{
    CmdParse _parse(g_nodeInfoFileName);
    if (_parse.IsOk())
    {
        while (_parse.HasNext()) {
            SimulatorCmd _re = _parse.GetNext();
            if (_re.m_nDataLenght == -1)
            {
                continue;
            }
            m_Cmds.append(_re);
        }
    } else {
        qDebug() <<"Parse Error!\n";
    }

}


void Simulator::SltStart()
{
    if (!m_Cmds.isEmpty())
    {
        m_timer.start();
    }
}


void Simulator::SltStop()
{
    m_timer.stop();
}

////
/// \brief Simulator::help_deleteTimeOutCmds 未启用
///
void Simulator::help_deleteTimeOutCmds()
{

}

///
/// \brief Simulator::help_doData
/// \param serialPortData_
///
void Simulator::help_doData(const SerialPortData &serialPortData_)
{
    switch(serialPortData_.cmd) {
    case SimulatorCmd::TEMPERATURE : sersor(serialPortData_.cmd,serialPortData_.data);break;
    case SimulatorCmd::NETWORKBUILD : netTopologyBuild(serialPortData_.type,serialPortData_.data);break;
    case SimulatorCmd::NETWORKTEST : netTopologyTest(serialPortData_.data);break;
    default:break;
    }
}

/////
/// \brief Simulator::sersor
/// \param flag
/// \param data
///
void Simulator::sersor(int flag, const QByteArray &data)
{
    QList<QByteArray> list = data.split('|');
    if (list.length() < 3) {

    } else {

        QString addr = list.at(0);
        ushort name = static_cast<ushort>(list.at(2).at(0));//设备名
        int value = list.at(1).toInt();



        // emit sig_sensorData(name,flag,value);
        emit sig_sensorData(addr,value);

        emit sig_items(addr,name,value,flag);


        emit sig_clear0(name);

        emit sig_sensorData(name,flag,value);


        if (!m_dataFilter.filtering(flag,value)) {
            emit sig_badData(name,flag,value);
        }


        qDebug() << "传感器数据" << addr << name << value;

        QString info = trUtf8("传感器数据-->设备名:%1 值:%2").arg(name).arg(value);
        qDebug() << info;
        emit sig_realTimeInfo(info);

    }

}


///
/// \brief Simulator::netTopologyBuild
/// \param type
/// \param data
///
void Simulator::netTopologyBuild(char type,const QByteArray &data)
{
    QList<QByteArray> list = data.split('|');
    if (list.length() < 3) return;
    QString addr = list.at(0);
    QString parentAddr = list.at(1);
    ushort name = (ushort)list.at(2).at(0);

    if (type == 'C') {
        addr = "0000";
    }

    emit sig_netTopologyBuild(type,addr,parentAddr,name);

    qDebug() << "网络建立" << addr << parentAddr << name;


    QString info = trUtf8("网络组建-->设备类型:%1 设备名:%2 节点地址:%3 父节点地址:%4").
            arg(type).arg(name).arg(addr).arg(parentAddr);


    qDebug() << info;
    emit sig_realTimeInfo(info);

}
///
/// \brief Simulator::netTopologyTest
/// \param data
///
void Simulator::netTopologyTest(const QByteArray &data)
{
    QList<QByteArray> list = data.split('|');
    if (list.length() < 3) return;
    QString addr = list.at(0);
    ushort name = (ushort)list.at(2).at(0);
    emit sig_netTopologyTest(addr,name);

    qDebug() << "网络测试" << addr << name;
}

/////
/// \brief Simulator::slt_addAfilte
/// \param f
///
void Simulator::slt_addAfilte(const Filter &f)
{
    m_dataFilter.addAFilter(f);
}
